﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Dapper;
using System.Data;
using MySql.Data.MySqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.Data.SqlClient;

///<summary>
///Dapper实例(采用单例模式)
/// </summary>
namespace Homework.Repository
{
    public  class DapperFactory
    {
        /// <summary>
        /// 读取配置文件用
        /// </summary>
        private IConfiguration configuration { get; set; }
        //返回连接实例
        private static IDbConnection dbConnection = null;
        //静态变量保存类的实例
        private static DapperFactory uniqueInstance;
        //定义一个标识确保线程同步
        private static readonly object locker = new object();
        /// <summary>
        /// 私有构造方法，使外界不能创建该类的实例，以便实现单例模式
        /// </summary>
        private DapperFactory()
        {
            configuration = new ConfigurationBuilder().Add(new JsonConfigurationSource
            {
                Path = "appsetting.json",
                ReloadOnChange=true
            }).Build();
        }
        /// <summary>
        /// 获取实例，这里是单例模式，保证只存在一个实例
        /// </summary>
        /// <returns></returns>
        public static DapperFactory GetInstance()
        {
            //双重锁定实现单例模式，在外层加个判空条件主要是为了减少加锁，释放锁的不必要的损耗
            if (uniqueInstance==null)
            {
                lock (locker)
                    {
                        if (uniqueInstance==null)
                        {
                            uniqueInstance = new DapperFactory();//懒汉模式
                        }
                    }
            }
            return uniqueInstance;
        }
        /// <summary>
        /// 创建数据库连接对象（采用了设计模式 之 工厂模式）
        /// </summary>
        /// <returns></returns>
        public IDbConnection GetDbConnection()
        {
            //如果数据库连接对象为空，则重新连接
            if (dbConnection==null)
            {
                //读取配置文件中的数据库服务器类型 mysql 或 sqlserver
                string dbType = configuration["DbServerType"];
                //读取配置文件中的连接字符串
                string _connectionString = configuration.GetConnectionString("conn");
                switch (dbType)
                {
                    case "Mysql":dbConnection = new MySqlConnection(_connectionString);
                    break;
                    case "SqlServer":dbConnection = new SqlConnection(_connectionString);
                    break;
                }
            }
            //判断连接状态（Dapper内部会自动打开数据库连接，所以无需以下代码）
            if (dbConnection.State==ConnectionState.Closed)
            {
                dbConnection.Open();
            }
            return dbConnection;
        }
    }
}
